import nocolor from '@/assets/nocolor.png'
import './index.css'
import { useState,useRef } from 'react';
import SvgPainter from './components/svgPainter';
import ToolBar from './components/toolbar/toolbar'
import { Button, Modal, message } from 'antd';
import {saveFile, dataURLtoBlob} from '@/js/file'
import { useKeyPress } from 'ahooks';
import JSZip from "jszip"
import { v4 } from 'uuid';
/**
 * 
 * @param {Object} param0 
 * @param {Array} param0.initData 初始化数据
 * @returns 
 */
function Editor ({initData}) {
    const [history, setHistory] = useState([]); // 操作记录 用来撤销与重做
    const [data, setDataState] = useState(initData) // 所有图像数据结构
    const [nowColor, setNowColor] = useState('blue') // 设置当前颜色
    const [lineWidth, setLineWidth] = useState(1) // 设置当前的线宽
    const [mode, setMode] = useState('draw')  // 模式 draw 瞎画 select 选中
    const [nowx, setNowx] = useState(0); // 有空时改用useMouse
    const [nowy, setNowy] = useState(0);
    const [mouseDownState, setMouseDownState ] = useState(false)
    const [saveFileModalVisible, setSaveFileModalVisible] = useState(false);
    const canvas = useRef(null);

    const undo = () => {
        if (data.length) {
            console.log('%c 撤销', 'color:#00f', data)
            const tempArray = [...data];
            const undoItem = tempArray.splice(tempArray.length - 1);
            setDataState(() => tempArray);
            const tempHistory =[...history];
            tempHistory.push(undoItem[0]);
            setHistory(() => tempHistory);
        }
    }
    const redo = () => {
        if (history.length) {
            const tempArray = [...history];
            const redoItem = tempArray.splice(tempArray.length - 1);
            setHistory(() => tempArray);
            const tempData =[...data];
            tempData.push(redoItem[0]);
            console.log('%c 看看恢复', 'color:#012', redoItem);
            setDataState(() => tempData);
        }
    }
    useKeyPress('meta.z',undo)
    useKeyPress('ctrl.z',undo)
    const onMouseDown = () => {
        console.log('%c 开始绘制', 'color: #003', nowColor,data.length);
        setMouseDownState(true);
        if (mode == 'draw') {
            setDataState(v => {
                console.log('%c 这是怎么了', 'color: #011', v);
                console.trace()
                // 不知道为啥这个方法总是被调用两次，先这样过滤一次
                v= v.filter(a => a.data.length)
                v.push({
                    type: 'path',
                    id: v4(),
                    width: lineWidth,
                    color: nowColor,
                    data: []
                })
                return v;
            })
        } 
        console.log('%c 帮助我们', 'color:#010',data)
    }
    const onMouseMove = (e) => {
        const lBase = canvas.current.offsetLeft
        const tBase = canvas.current.offsetTop
        const nowX = e.clientX-lBase;
        const nowY = e.clientY-tBase;
        setNowx(nowX)
        setNowy(nowY)
        if (mouseDownState) {
            // console.log("%c 为什么不画呢", 'color: #002',data)
            if (mode == 'draw') {
                setDataState(v=> {
                    // console.log('%c 应该调了吧', 'color:#003')
                    v[v.length-1].data.push([e.clientX-lBase, e.clientY-tBase]);
                    return v
                })
            }
        }
        // console.log('%c 这里面有啥', 'color: #000', e.clientX-lBase, e.clientY-tBase)
    }
    const test = () => {
        
        console.log('%c 看看元素', 'color: #001', canvas);
    } 
    const setColor = (v) => {
        setNowColor(v);
        console.log('%c 设置颜色', 'color: #002',v)
    }
    const saveSvg = () => {
        console.log('%c 保存svg', 'color: #005', canvas);
        saveFile(canvas.current.innerHTML, {
            desc: "SVG矢量图形",
            ext: ".svg"
        })
    }
    const saveQtu = () => {
        const zip = new JSZip();
        zip.file('index.json', JSON.stringify(data));
        zip.generateAsync({type: 'blob'}).then(v => {
            saveFile(v, {
                desc: 'qtu项目',
                ext: '.qtu',
                type: 'blob'
            })
        })
    }
    const savePng = () => {
        // const container = document.createDocumentFragment();
        const canvas=document.querySelector('#preciew')
        // canvas.height=600;
        // canvas.width =800;
        // container.appendChild(canvas);
        
        // canvas.toDataURL()
        canvas.toBlob(v => {
            saveFile(v, {
                desc: "png图片",
                ext: ".png"
            })
        })
    }
    const showSaveFileModal = () => {
        setSaveFileModalVisible(true)
        setTimeout(() => {
            const canvas=document.querySelector('#preciew')
            const ctx = canvas.getContext('2d');
            data.forEach(v => {
                switch (v.type) {
                    case 'path':
                        ctx.strokeStyle=v.color;
                        ctx.lineWidth = v.width
                        ctx.beginPath(); 
                        v.data.forEach((a,i)=> {
                            if (i) {
                                ctx.lineTo(a[0],a[1])
                            } else {
                                ctx.moveTo(a[0],a[1])
                            }
                        })
                        ctx.stroke();
                        // return (<Path lines={v.data} stroke={v.color} />);
                        break;
                    default:
                        message.error('有未知元素。请升级版本')
                        return []
                }
            });
        }, 100)
    }
    const changeElement = (v) => {
        const newData = [...data];
        const i = newData.findIndex(a => a.id ===v.id);
        newData[i] = v;
        setDataState(() => newData);
    }
    return (<div className='editor overflow-hidden' onClick={test}>
        <div
            style={{height: 600, width: 800,backgroundImage:`url(${nocolor})`}}
            onMouseMove={onMouseMove}
            ref={canvas}
            onMouseDown={onMouseDown}
            onMouseUp={() => setMouseDownState(false)}
        >
            <SvgPainter data={data} mode={mode} change={changeElement} />
        </div>
        <div style={{color: 'black'}}>{nowx}, {nowy}</div>
        <ToolBar
          setColor={setColor}
          saveFile={showSaveFileModal}
          undo={undo}
          redo={redo}
          nowColor={nowColor}
          lineWidth={lineWidth}
          changeLineWidth={setLineWidth}
          mode={mode}
          setMode={setMode}
        />
        <Modal title="文件保存" footer={null} open={saveFileModalVisible} onCancel={() => setSaveFileModalVisible(false)}>
            <div className='flex'>
                <div className='flex flex-col gap-y-2'>
                    <Button type="primary" onClick={saveQtu}>保存为qtu项目</Button>
                    <Button type="primary" onClick={saveSvg}>导出为svg文件</Button>
                    <Button type="primary" onClick={savePng}>导出为png文件</Button>
                </div>
                <div>
                    <canvas id='preciew' width={800} height={600} className='w-full'></canvas>
                </div>
            </div>
        </Modal>
    </div>)
}

export default Editor;